<template>
  <div>
    <div class="search">
      <van-nav-bar left-arrow
                   @click-left="$router.go(-1)" />
      <van-search v-model="keyword"
                  show-action
                  label="地址"
                  placeholder="请输入搜索关键词"
                  @search="onSearch">
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
      </van-search>
    </div>
    <div class="hisWrap">
      <div class="title">热门搜索</div>
      <ul class="hisitems">
        <li class="item"
            v-for="(keyWords, index) in hisKeyword"
            :key="index"
            @click="findItems(keyWords)">{{keyWords}}</li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: 'search',
  data () {
    return {
      keyword: '',
      hisKeyword: localStorage.getItem('hisWords') ? JSON.parse(localStorage.getItem('hisWords')) : []
    }
  },
  methods: {
    findItems (keyWords) {
      this.keyword = keyWords
      this.onSearch()
    },
    onSearch () {
      // 存数据 先取在添加
      let hisWords = localStorage.getItem('hisWords') ? JSON.parse(localStorage.getItem('hisWords')) : []
      // 添加数据
      hisWords.unshift(this.keyword)
      hisWords = [...new Set(hisWords)]
      if (hisWords.length >= 10) {
        hisWords.length = 10
      }

      // 存数据
      localStorage.setItem('hisWords', JSON.stringify(hisWords))

      this.$router.push({
        path: '/searchitems',
        query: {
          keyword: this.keyword
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.search {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  .van-nav-bar {
    width: 20px;
    /deep/ .van-nav-bar__left {
      padding-left: 5px;
      .van-icon {
        color: #999;
        font-size: 20px;
      }
    }
  }
  .van-search {
    flex: 1;
    .van-search__content {
      border-radius: 15px;
    }
    .van-search__action {
      width: 60px;
      height: 28px;
      border-radius: 15px;
      background-color: #ff734c;
      color: #fff;
      text-align: center;
      line-height: 28px;
    }
  }
}

.hisWrap {
  .title {
    margin: 18px 0 16px;
    padding: 0px 12px;
    font-size: 14px;
  }
  .hisitems {
    display: flex;
    flex-wrap: wrap;
    margin: 0 12px;
    .item {
      background-color: #e9ecf0;
      margin: 0 10px 10px 0;
      padding: 8px 12px;
    }
  }
}
</style>
